package cn.javaweb.servlet;

import cn.javaweb.entity.PasswordInfo;
import cn.javaweb.entity.User;
import cn.javaweb.library.AjaxResult;
import cn.javaweb.library.Util;
import cn.javaweb.model.UserModel;
import com.alibaba.fastjson2.JSON;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;

@WebServlet("/user/resetpwd")
public class ResetPwdServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try{

            PasswordInfo pi = JSON.parseObject(Util.getJsonParam(req), PasswordInfo.class);

            User user = (User) req.getAttribute("user");
            if(!user.getPassword().equals(pi.getOldpwd())){
                resp.getWriter().print(AjaxResult.error("原密码不正确"));
                return;
            }

            UserModel userModel = new UserModel();
            user.setPassword(pi.getNewpwd());
            userModel.updateUserPassword(user);
            resp.getWriter().print(AjaxResult.success("密码更新成功"));
        }catch (Exception e){
            resp.getWriter().print(AjaxResult.error("登陆失败"));
        }
    }
}
